<?php
// +----------------------------------------------------------------------
// | CoreThink [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.corethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: jry <598821125@qq.com> <http://www.corethink.cn>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use Think\Controller;
// 引入鉴权类
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;

/**
 * 上传控制器
 * @author hdj
 */
class UploadfileController extends Controller
{
    /**
     * 上传
     */
    public function upload()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->rootPath = './Uploads/images/'; // 设置附件上传根目录
        $upload->savePath = ''; // 设置附件上传（子）目录
        // 上传文件
        $info = $upload->upload();
        $info = $info['imgFile'];
        //拼接本地完整地址
        $filePath = getcwd()."/uploads/images/" . $info['savepath'] . $info['savename'];


        //调用七牛sdk执行上传到七牛
        $this->qiniu_upload($filePath);
        //前端显示图片地址
        $info['real_path'] = 'http://oz8rilu2x.bkt.clouddn.com/' . $info['savename'];

        $this->ajaxReturn($info);
    }

    private function qiniu_upload($filePath)
    {

// 需要填写你的 Access Key 和 Secret Key
        $accessKey = "AWNxui9ZTO9ZE1ibXcBjapNtMZzSJ6YYCp0oQe5U";
        $secretKey = "fR1yCppY7ZBxjCqMVgxc1qjOI_TU0RymdoBLBqbN";
        $bucket = "liu198787";
// 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
// 生成上传 Token
        $token = $auth->uploadToken($bucket);

// 上传到七牛后保存的文件名
        $key = basename($filePath);
// 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
// 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
        unlink($filePath);
    }

}